<template>
    <div>
        <el-button type="primary" @click="openDialog">新增图书</el-button>
        <el-table :data="books" style="width: 100%; margin-top: 16px;" border
            :header-cell-style="{ textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column prop="title" label="书名" min-width="120" fixed="left" />
            <!-- 其它列... -->
            <el-table-column label="操作" min-width="140" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" @click="onEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="onDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <BookFormDialog :visible="dialogVisible" :form="bookForm" :categories="categories" :publishers="publishers"
            @submit="handleSubmit" @update:visible="val => { if (!val) onDialogClose() }" />
    </div>
</template>

<script setup>
import { ref } from 'vue'
import BookFormDialog from '@/components/BookFormDialog.vue'

const dialogVisible = ref(false)
const bookForm = ref({
    title: '',
    author: '',
    isbn: '',
    category: null,
    publisher: null,
    publishYear: null,
    status: '在馆'
})
const categories = ref([
    { id: 1, name: '文学' },
    { id: 2, name: '科学' }
])
const publishers = ref([
    { id: 1, name: '出版社A' },
    { id: 2, name: '出版社B' }
])
const books = ref([])

const resetBookForm = () => {
    bookForm.value = {
        title: '',
        author: '',
        isbn: '',
        category: null,
        publisher: null,
        publishYear: null,
        status: '在馆'
    }
}

const onDialogClose = () => {
    dialogVisible.value = false
    resetBookForm()
}

const openDialog = () => {
    resetBookForm()
    dialogVisible.value = true
}

const handleSubmit = (newBook) => {
    dialogVisible.value = false
    resetBookForm()
}

const onEdit = (row) => {
    // 重新实现编辑逻辑，保证下拉框引用一致
    const categoryObj = categories.value.find(c => c.id === (row.category?.id || row.category)) || null
    const publisherObj = publishers.value.find(p => p.id === (row.publisher?.id || row.publisher)) || null
    bookForm.value = {
        id: row.id,
        title: row.title,
        author: row.author,
        isbn: row.isbn,
        category: categoryObj,
        publisher: publisherObj,
        publishYear: row.publishYear,
        status: row.status
    }
    dialogVisible.value = true
}

const onDelete = (row) => {
    // 删除逻辑
}
</script>
